import os
from bs4 import BeautifulSoup
import re


'''
批量修改html文件名称，并删除不必要的html内容
'''
def extract_og_title(html_file):
    with open(html_file, 'r', encoding='utf-8') as f:
        soup = BeautifulSoup(f, 'html.parser')
        meta_tag = soup.find('meta', property='og:title')
        if meta_tag:
            # 使用正则表达式替换特殊字符
            title = meta_tag.get('content')
            new_title = re.sub(r'[<>:"/\\|?*]', '', title)
            return new_title
        else:
            return None

def remove_div_h1_tags(html_file):
    with open(html_file, 'r', encoding='utf-8') as f:
        soup = BeautifulSoup(f, 'html.parser')
        # 删除指定的 <div> 标签
        div_tag = soup.find('div', id='fatkun-drop-panel')
        if div_tag:
            div_tag.decompose()
        # 删除指定的 <h1> 标签及其后面的内容
        h1_tag = soup.find('h1', id='666-彩蛋')
        if h1_tag:
            h1_tag.decompose()
        # 删除包含 title="知识星球" 的 <a> 标签
        a_tags = soup.find_all('a', title='知识星球')
        for a_tag in a_tags:
            a_tag.decompose()
        # 保存修改后的 HTML 内容到文件中
        with open(html_file, 'w', encoding='utf-8') as f:
            f.write(soup.prettify())


def rename_html_files(folder):
    for filename in os.listdir(folder):
        if filename.endswith('.html'):
            html_file = os.path.join(folder, filename)
            remove_div_h1_tags(html_file)
            new_filename = extract_og_title(html_file)
            if new_filename:
                new_filename = new_filename.strip() + '.html'
                os.rename(html_file, os.path.join(folder, new_filename))
                print(f"Renamed {filename} to {new_filename}")

def main():
    # 设置 HTML 文件所在的文件夹路径
    folder_path = r'E:\资料-学习\1.信息技术资料\芋道\源码系列\《数据库实体》'
    rename_html_files(folder_path)

if __name__ == "__main__":
    main()
